﻿
using UnityEngine;

/// <summary>
/// Tween the widget's size.
/// </summary>

[RequireComponent(typeof(RectTransform))]
[AddComponentMenu("UGUI/Tween/Tween Y")]
public class UGUITweenY : UGUITweener
{
    public override object fromValue { get { return from; } set { from = (float)value; } }
    public override object toValue { get { return to; } set { to = (float)value; } }

    public float from = 0;
    public float to = 0;
    public bool updateTable = false;

    RectTransform mWidget;

    public RectTransform cachedWidget { get { if (mWidget == null) mWidget = GetComponent<RectTransform>(); return mWidget; } }
    protected override void Start()
    {
        if (delay == 0)
        {
            value = from;
        }
        base.Start();
    }

    /// <summary>
    /// Tween's current value.
    /// </summary>
    public float value
    {
        get
        {
            return (int)cachedWidget.anchoredPosition.y;
        }
        set
        {
            var anchoredPosition = cachedWidget.anchoredPosition;
            anchoredPosition.y = value;

            cachedWidget.anchoredPosition = anchoredPosition;
        }
    }

    /// <summary>
    /// Tween the value.
    /// </summary>
    protected override void OnUpdate(float factor, bool isFinished)
    {
        value = Mathf.RoundToInt(from * (1f - factor) + to * factor);
    }

    /// <summary>
    /// Start the tweening operation.
    /// </summary>

    static public UGUITweenWidth Begin(RectTransform widget, float duration, int y)
    {
        UGUITweenWidth comp = UGUITweener.Begin<UGUITweenWidth>(widget.gameObject, duration);
        comp.from = (int)widget.anchoredPosition.y;
        comp.to = y;

        if (duration <= 0f)
        {
            comp.Sample(1f, true);
            comp.enabled = false;
        }
        return comp;
    }

    [ContextMenu("Set 'From' to current value")]
    public override void SetStartToCurrentValue() { from = value; }

    [ContextMenu("Set 'To' to current value")]
    public override void SetEndToCurrentValue() { to = value; }

    [ContextMenu("Assume value of 'From'")]
    void SetCurrentValueToStart() { value = from; }

    [ContextMenu("Assume value of 'To'")]
    void SetCurrentValueToEnd() { value = to; }
}
